const http=require("http");
const fs=require("fs");
const qs=require("querystring");
const url=require("url");

// 路由设置
    // 数据请求：http://localhost:3000/api
    // 静态网页请求：http://localhost:3000/

    http.createServer((req,res)=>{
        if(req.url.includes("/api")){
            dateHandle(req,res);
        }else{
            staticHandle(req,res)
        }
    }).listen(3000,()=>{
        console.log("服务器挂载成功：http://localhost:3000")
    })

    function dateHandle(req,res){
        if(req.method === "GET"){
            const obj = url.parse(req.url, true).query;
            fn(req, res, obj);
        }else if(req.method === "POST"){
            let str = "";
            req.on("data",(d)=>{
                str += d;
            })
            req.on("end", ()=>{
                const obj = qs.parse(str);
                fn(req, res, obj);
            })
        }
    }

    function staticHandle(req,res){
        fs.readFile("./www" + url.parse(req.url).pathname, (err, data)=>{
            if(err){
                res.write("404");
            }else{
                res.write(data);
            }
            res.end();
        })
    }

    function fn(req,res,date){
        console.log(date);
        res.end();
    }
